package cn.topcode.controller;

import cn.topcode.beans.dto.Dto;
import cn.topcode.beans.pojo.User;
import cn.topcode.beans.vo.userVO.UserRegisterVO;
import cn.topcode.service.RpcUserService;
import cn.topcode.service.SmsService;
import cn.topcode.service.user.TokenService;
import cn.topcode.service.user.UserService;
import cn.topcode.utils.*;
import com.alibaba.dubbo.config.annotation.Reference;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.regex.Pattern;

@RestController
public class UserController {

    @Reference
    private RpcUserService rpcUserService;
    @Resource
    private SmsService smsService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private UserService userService;
    @Resource
    private TokenService tokenService;


    @ApiOperation(value = "用户登录", httpMethod = "POST",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "手机登录")
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public Dto login(@RequestParam String phone, @RequestParam String password, HttpServletRequest request) {
        User user=null;
        if(EmptyUtils.isEmpty(phone)){
            return DtoUtil.returnFail("手机号不能为空！","A001");
        }
        if(!validPhone(phone)){
            return DtoUtil.returnFail("手机号格式不正确","A002");
        }
        if(EmptyUtils.isEmpty(password)){
            return DtoUtil.returnFail("密码不能为空！","A003");
        }

        try {
             user=userService.login(phone, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail("登录失败","A000");
        }else{
            String userAgent=request.getHeader("userAgent");
            try {
                String token=tokenService.generateToken(userAgent,user);
                tokenService.saveToken(token,user);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }



        return DtoUtil.returnSuccess("成功");
    }

    /***
     * 用户注册
     * @param userRegisterVO
     * @return
     */
    @ApiOperation(value = "用户注册", httpMethod = "POST",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "注册类型:手机")
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = "application/json")
    public Dto register(@RequestBody UserRegisterVO userRegisterVO) {
        if (null == userRegisterVO.getPhone() || "".equals(userRegisterVO.getPhone()))
            return DtoUtil.returnFail("请输入手机号", Constants.Register.USER_IS_NULL);
        if (!validPhone(userRegisterVO.getPhone()))
            return DtoUtil.returnFail("请使用正确的手机号注册", Constants.Register.USER_IS_NOT);
        if (null == userRegisterVO.getCode() || "".equals(userRegisterVO.getCode()))
            return DtoUtil.returnFail("请输入注册码", Constants.Register.CODE_IS_NULL);
        if (!userRegisterVO.getCode().equals(redisUtils.get("activation:" + userRegisterVO.getPhone())))
            return DtoUtil.returnFail("注册码不对", Constants.Register.CODE_IS_NOT);
        userRegisterVO.setCreateDate(new Date());
        try {
            if (rpcUserService.registerUser(userRegisterVO)) {
                redisUtils.delete("activation:" + userRegisterVO.getPhone());
                return DtoUtil.returnSuccess("注册成功！");
            }
            return DtoUtil.returnFail("注册失败", Constants.Register.REGISTER_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), Constants.SYSTEM_ERROR);
        }
    }

    /***
     * 获取注册码
     * @param phone 手机号
     * @return
     */
    @ApiOperation(value = "获取注册码", httpMethod = "GET",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "注册类型:手机")
    @RequestMapping(value = "/getCode", method = RequestMethod.GET, produces = "application/json")
    public Dto getCode(@ApiParam(name = "phone", value = "手机号", required = true)
                       @RequestParam String phone) {
        if (null == phone || "".equals(phone))
            return DtoUtil.returnFail("请输入手机号", Constants.Register.USER_IS_NULL);
        if (!validPhone(phone))
            return DtoUtil.returnFail("请使用正确的手机号注册", Constants.Register.USER_IS_NOT);
        String code = String.valueOf(MD5.getRandomCode());
        try {
            if (rpcUserService.validateUser(phone))
                return DtoUtil.returnFail("手机号已注册", Constants.Register.USER_IS_EXIST);
            smsService.send(phone, "1", new String[]{code, String.valueOf("3")});
            redisUtils.set("activation:" + phone, 180, code);
            return DtoUtil.returnSuccess("获取验证码成功");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), Constants.SYSTEM_ERROR);
        }
    }

    /***
     * 验证是否合法的手机号
     * @param phone 手机号
     * @return
     */
    private boolean validPhone(String phone) {
        String regex = "^1[3578]{1}\\d{9}$";
        return Pattern.compile(regex).matcher(phone).find();
    }
}
